package com.jboost.modules.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jboost.common.constant.CommonConstant;
import com.jboost.common.system.api.ISysBaseAPI;
import com.jboost.common.system.vo.LoginUser;
import com.jboost.modules.system.constant.SysUserActionEnum;
import com.jboost.modules.system.entity.SysUser;
import com.jboost.modules.system.entity.SysUserLog;
import com.jboost.modules.system.mapper.SysUserLogMapper;
import com.jboost.modules.system.service.ISysUserLogService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 机构日志
 * @Author: jeecg-boot
 * @Date:   2022-10-09
 * @Version: V1.0
 */
@Service
public class SysUserLogServiceImpl extends ServiceImpl<SysUserLogMapper, SysUserLog> implements ISysUserLogService {

    @Resource
    private ISysBaseAPI baseAPI;

    @Override
    public void addBy(SysUser SysUser, SysUserActionEnum action, String remark) {
        SysUserLog log = new SysUserLog();
        log.setUserId(SysUser.getId());
        log.setAction(action.getCode());
        log.setRemark(remark);

        log.setSnapshot(JSONObject.toJSONString(SysUser));
        this.save(log);

    }

    @Override
    public void addById(String id, SysUserActionEnum action, String remark) {
        SysUserLog log = new SysUserLog();
        log.setUserId(id);
        log.setAction(action.getCode());
        log.setRemark(remark);

        this.save(log);
    }

    @Override
    public List<SysUserLog> listBySysUserId(String id) {
        List<SysUserLog> logList = this.lambdaQuery().eq(SysUserLog::getUserId,id).list();
        if (CollUtil.isEmpty(logList)){
            return new ArrayList<>();
        }
        String [] userNames = logList.stream().map(SysUserLog::getCreateBy).toArray(String[]::new);
        List<LoginUser> userList = baseAPI.queryUserByIdsOrNames(userNames);
        logList.forEach(log->{
            LoginUser user = userList.stream().filter(u->u.getUsername().equals(log.getCreateBy())||u.getId().equals(log.getCreateBy())).findFirst().orElse(null);
            if (null!=user){
                log.setCreateBy(user.getRealname()+"（"+user.getUsername()+"）");
            }else {
                log.setCreateBy(CommonConstant.UNDIFIND_DEFALUT +"（"+user.getUsername()+"）");
            }
        });
        return logList;
    }
}
